<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Login
 * 
 * Show the login page / process login actions.
 */
class escape_repositoryui_action_Login extends escape_repositoryui_Action
{
	public function handleRequest()
	{
		// PHP4 code in the php-openid library causes a lot of warnings
		error_reporting(E_ALL ^ E_COMPILE_WARNING ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
		require_once("php-openid-2/include.php");
		
		session_start();
		
		/* @var $repository escape_repository_Repository */
		$repository =& $this->requestAttributes['repository'];
		/* @var $repositoryUi escape_repositoryui_RepositoryUi */
		$repositoryUi =& $this->requestAttributes['repositoryUi'];
		
		// get the error messages queue
		$errorMessages =& $this->requestAttributes['errorMessages'];
		if(!isset($errorMessages))
		{
			$errorMessages = array();
		}
		
		$returnUrl = $repository->config['server_url'];
		$aggregation = null;
		if(isset($_REQUEST['return_url']))
		{
			$returnUrl = $_REQUEST['return_url'];
			
			// attempt to fetch the aggregation from the return URL so we can use the right template for the login screen
			try
			{
				if(preg_match('~' . preg_quote($repository->config['server_url'], '~') . '/(show|graph)/([^?#]+)~i', $returnUrl, $matches))
				{
					$objectId = $matches[2];
					$objectUri = $repository->convertDataObjectIdToObjectUri($objectId);
					
					$oreObject = $repository->getOreObjectByUri($objectUri);
					$this->requestAttributes['oreObject'] =& $oreObject;
					$aggregation = $oreObject->getAggregation();
					$this->requestAttributes['aggregation'] =& $aggregation;
				}
			}
			catch(Exception $ex)
			{
				// ignore
			}
		}
		
		$signupUrl = $repository->config['server_url'] . '/signup?return_url=' . rawurlencode($returnUrl);
		
		$this->requestAttributes['returnUrl'] = $returnUrl;
		$this->requestAttributes['signupUrl'] = $signupUrl;
		
		
		// check which authentication mechanisms are enabled
		if(!$repository->config['localauthn_enabled'])
		{
			if($repository->config['saml']['enabled'])
			{
				// only SAML is enabled, redirect to SAML
				$beginSamlUrl = $repository->config['server_url'] . '/beginSamlLogin?return_url=' . rawurlencode($returnUrl);
				header("Location: " . $beginSamlUrl);
				return null;
			}
			else
			{
				// no authentication mechnisms are enabled!
				$repositoryUi->displayErrorPage('All authentication mechanisms are disabled.');
				return null;
			}
		}

		
		$verb = null;
		if(isset($_REQUEST['verb']))
		{
			$verb = $_REQUEST['verb'];
		}
		
		if($verb === 'beginLocal')
		{
			// process local login
			
			if(!isset($_REQUEST['userid']) || $_REQUEST['userid'] == '')
			{
				$errorMessages[] = 'Please provide a user ID';
			}
			if(!isset($_REQUEST['password']) || $_REQUEST['password'] == '')
			{
				$errorMessages[] = 'Please provide a password';
			}
			
			if(count($errorMessages) === 0)
			{
				$userId = $_REQUEST['userid'];
				$password = $_REQUEST['password'];
				
				$userUri = $repository->convertUserObjectIdToObjectUri($userId);
	
				$user = null;
				try
				{
					$user = $repository->getUserByUri($userUri);
				}
				catch(fedora_exception_InvalidFedoraPid $exception)
				{
					//ignore
				}
				catch(escape_repository_exception_NotFound $exception)
				{
					//ignore
				}
				
				if($user === null)
				{
					$errorMessages[] = 'User \'' . htmlspecialchars($userId) . '\' does not exist';
				}
				else
				{
					if($user->checkPassword($password))
					{
						$_SESSION['user_uri'] = $user->getUri();
	
						header("Location: " . $returnUrl);
						
						return null;
					}
					else
					{
						$errorMessages[] = 'Incorrect password';
					}
				}
			}
		}
		
		$this->requestAttributes['errorMessages'] =& $errorMessages;
		
		return 'LoginForm';
	}
}